package com.demo.lock;

import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * @author LiYuhang
 * @version 0.1
 * @application
 * @Date 2020/12/26 22:44
 */
public class ReadLockJumpQueue {
    private static final ReentrantReadWriteLock reentrantReadWriteLock = new ReentrantReadWriteLock();
    private static final ReentrantReadWriteLock.ReadLock readLock = reentrantReadWriteLock.readLock();
    private static final ReentrantReadWriteLock.WriteLock writeLock = reentrantReadWriteLock.writeLock();
    public static  Boolean loading=false;
    private static void read() {
        readLock.lock();
        try {
            System.out.println(Thread.currentThread().getName() + "得到读锁，正在读取");
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            System.out.println(Thread.currentThread().getName() + "释放读锁");
            readLock.unlock();
        }
    }
    private static void write() {
        if(loading){
            System.out.println("未抢到资源，拒绝");
            return;
        }
        writeLock.lock();
        try {
            loading=true;
            System.out.println(Thread.currentThread().getName() + "得到写锁，正在写入");
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            loading=false;
            e.printStackTrace();
        } finally {
            loading=false;
            System.out.println(Thread.currentThread().getName() + "释放写锁");
            writeLock.unlock();
        }
    }
    public static void main(String[] args) throws InterruptedException {
//        new Thread(() -> read(),"Thread-2").start();
//        new Thread(() -> read(),"Thread-4").start();
        new Thread(() -> write(),"Thread-0").start();
        new Thread(() -> write(),"Thread-1").start();
        new Thread(() -> write(),"Thread-2").start();
        new Thread(() -> write(),"Thread-3").start();
        new Thread(() -> write(),"Thread-4").start();
        new Thread(() -> write(),"Thread-5").start();
        new Thread(() -> write(),"Thread-6").start();
        new Thread(() -> write(),"Thread-7").start();
//        new Thread(() -> read(),"Thread-5").start();
    }
}
